package org.spring.springcloud.config;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.spring.springcloud.domain.User;
import org.spring.springcloud.domain.UserEntity;
import org.spring.springcloud.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;
    /**
     * 登录验证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //第一步：authenticationToken里面存放的是我们前台输入的账号密码,把 AuthenticationToken 转换为 UsernamePasswordToken
        UsernamePasswordToken upToken = (UsernamePasswordToken) authenticationToken;
        String userName = String.valueOf(upToken.getPrincipal());
        String passwd = String.valueOf(upToken.getCredentials());
        //第二步： 从 UsernamePasswordToken 中来获取 username
        String username = upToken.getUsername();
        System.out.println("username="+userName+"-------" +"passwd="+passwd);

        //第三步. 调用数据库的方法, 从数据库中查询 username 对应的用户记录
         UserEntity user = userService.findUserByUserName(username);

        //第四步. 若用户不存在, 则可以抛出 UnknownAccountException 异常
        if(user == null){
            System.out.println("用户不存在");
            throw new UnknownAccountException("用户不存在!");
        }

        //第五步. 根据用户信息的情况, 决定是否需要抛出其他的 AuthenticationException 异常.
//        if(user.getStatus()==2){
//            System.out.println("用户被冻结");
//            throw new LockedAccountException("用户被冻结");
//        }

        //第六步. 根据用户的情况, 来构建 AuthenticationInfo 对象并返回. 通常使用的实现类为: SimpleAuthenticationInfo

        Object principal = user;
        //2). credentials: 密码.
        Object credentials = user.getPassword(); //"fc1709d0a95a6be30bc5926fdb7f22f4";

        //3). realmName: 当前 realm 对象的 name. 调用父类的 getName() 方法即可
        String realmName = getName();
        //4). 盐值.
        ByteSource credentialsSalt = ByteSource.Util.bytes(username);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, realmName);
       // info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
}
